package com.xinxin.base.util;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;

/**
 * 时间工具类
 *
 * @author ys
 * @date 2020/5/13
 */
public class DateTimeUtil {

    public static final String FULL_TIME_PATTERN = "yyyyMMddHHmmss";
    public static final String FULL_TIME_SPLIT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static final String CST_TIME_PATTERN = "EEE MMM dd HH:mm:ss zzz yyyy";
    public static final String US_TIME_PATTERN = "EEE, dd MMM yyyy HH:mm:ss Z";

    public static final ZoneId UTC_ZONE = ZoneId.of("UTC");
    public static final ZoneId CST_ZONE = ZoneId.of("+8");

    public static final ZoneOffset UTC_OFFSET = ZoneOffset.UTC;
    public static final ZoneOffset CST_OFFSET = ZoneOffset.ofHours(8);

    public static void main(String[] args) {
        long timestamp = 1_622_505_751L * 1000;
        LocalDateTime localDateTime = DateTimeUtil.parseTimestamp(timestamp);
        System.out.println(DateTimeUtil.formatTime(localDateTime, DateTimeUtil.FULL_TIME_SPLIT_PATTERN));

        String usTime = "Tue, 01 Jun 2021 00:02:31 +0000";
        LocalDateTime utcDateTime = DateTimeUtil.parseTime(usTime, DateTimeUtil.US_TIME_PATTERN);
        localDateTime = DateTimeUtil.convertFromUTC(utcDateTime, DateTimeUtil.CST_ZONE);
        System.out.println(DateTimeUtil.formatTime(localDateTime, DateTimeUtil.FULL_TIME_SPLIT_PATTERN));
    }

    public static String formatTime(Date date, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.CHINA);
        return simpleDateFormat.format(date);
    }

    public static String formatTime(LocalDateTime localDateTime, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern, Locale.CHINA);
        return localDateTime.format(dateTimeFormatter);
    }

    public static LocalDateTime parseTime(String datetime, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern, Locale.US);
        return LocalDateTime.parse(datetime, dateTimeFormatter);
    }

    public static LocalDateTime parseTimestamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, CST_ZONE);
    }

    public static LocalDateTime convertFromUTC(LocalDateTime utcDateTime, ZoneId zoneId) {
        Instant instant = utcDateTime.toInstant(UTC_OFFSET);
        return LocalDateTime.ofInstant(instant, zoneId);
    }

    public static LocalDateTime convertToUTC(LocalDateTime localDateTime, ZoneOffset zoneOffset) {
        Instant instant = localDateTime.toInstant(zoneOffset);
        return LocalDateTime.ofInstant(instant, UTC_ZONE);
    }
}
